package com.ruoyi.framework.config;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WeChatPayConfig {

    @Value("${pay.wechat.mchid}")
    private String mchid;
    @Value("${pay.wechat.private_key_path}")
    private String privateKeyPath;
    @Value("${pay.wechat.merchant_serial_number}")
    private String merchantSerialNumber;
    @Value("${pay.wechat.api_v3key}")
    private String apiV3key;

    @Bean
    @ConditionalOnProperty(value = "pay.wechat.enabled", havingValue = "true")
    public RSAAutoCertificateConfig rsaAutoCertificateConfig() {
        RSAAutoCertificateConfig config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(mchid)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3key)
                        .build();
        return config;
    }

    /**
     * 支付
     *
     * @param rsaAutoCertificateConfig
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "pay.wechat.enabled", havingValue = "true")
    public JsapiServiceExtension jsapiServiceExtension(RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        JsapiServiceExtension service = new JsapiServiceExtension.Builder()
                .config(rsaAutoCertificateConfig)
                .signType("RSA") // 不填默认为RSA
                .build();
        return service;
    }

    /**
     * 退款
     *
     * @param rsaAutoCertificateConfig
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "pay.wechat.enabled", havingValue = "true")
    public RefundService refundService(RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        return new RefundService.Builder().config(rsaAutoCertificateConfig).build();
    }
}
